package cn.qingyun.gis.modules.init.system.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.qingyun.gis.cache.common.facade.CacheFacade;
import cn.qingyun.gis.common.Result;
import cn.qingyun.gis.modules.init.system.constant.CommonConstant;
import cn.qingyun.gis.modules.init.system.entity.SysUser;
import cn.qingyun.gis.modules.init.system.model.SysPhoneModel;
import cn.qingyun.gis.modules.init.system.service.IBaseCommonService;
import cn.qingyun.gis.modules.init.system.service.ISysUserService;
import cn.qingyun.gis.modules.init.system.vo.LoginUser;
import cn.qingyun.gis.modules.init.utils.EmailSender;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Objects;


@RestController
@RequestMapping("/admin/phone")
@Api(tags = "手机登录")
@Slf4j
public class PhoneController {

    private static final String CODE_CACHE_KEY = "LOGIN:CODE:%s";
    @Resource
    private ISysUserService iSysUserService;
    @Resource
    private IBaseCommonService baseCommonService;


    @ApiOperation("登录接口")
    @RequestMapping(value = "/sendCode", method = RequestMethod.GET)
    public Result<?> sendCode(@RequestParam("phone") String phone) {
        boolean isValid = ReUtil.isMatch("^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$", phone);
        if (!isValid) {
            return Result.error("非法的手机号");
        }

        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUser::getPhone, phone);

        SysUser sysUser = iSysUserService.getOne(queryWrapper);

        if (Objects.isNull(sysUser)) {
            return Result.error("该手机号未注册联创用户，请联系管理员。");
        }

        String userEmail = sysUser.getEmail();
        if (StrUtil.isBlank(userEmail)) {
            return Result.error("用户未维护邮箱地址，请联系管理员。");
        }

        Object cachedCode = CacheFacade.get(String.format(CODE_CACHE_KEY, phone));
        if (Objects.nonNull(cachedCode)) {
            return Result.error("10分钟内不可重复发送，请登录企业邮箱查看验证码。");
        }

        int randomInt = RandomUtil.randomInt(1000, 9999);

        new Thread(() -> {
            try {
                CacheFacade.set(String.format(CODE_CACHE_KEY, phone), randomInt, 10 * 60);
                EmailSender.sendCommonEmail(userEmail, String.format("尊敬的用户 %s 您好，欢迎登录联创效能平台，您的本次校验码为：【%s】, 请尽快登录，防止验证码失效(10分钟)。", sysUser.getUsername(), randomInt), "联创登录验证码");
            } catch (IOException e) {
                CacheFacade.delete(String.format(CODE_CACHE_KEY, phone));
                log.error("验证码发送失败，请稍后再试。", e);
            }
        }).start();

        return Result.ok(String.format("验证码已经发送到邮箱(%s), 请注意查收", userEmail));
    }

    @ApiOperation("登录接口")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result<?> login(@RequestBody SysPhoneModel phoneModel) {
        // 校验验证码
        String phone = phoneModel.getPhone();
        Integer code = phoneModel.getCode();
        Assert.notNull(phone, "请输入手机号");
        Assert.notNull(code, "请输入验证码");

        Object cachedCode = CacheFacade.get(String.format(CODE_CACHE_KEY, phone));
        if (!code.equals(cachedCode)) {
            return Result.error("验证码校验失败。");
        }

        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getPhone, phone);
        SysUser sysUser = iSysUserService.getOne(queryWrapper);

        Result<JSONObject> result = iSysUserService.checkUserIsEffective(sysUser);
        if (!result.getSuccess()) {
            return result;
        }

        //用户登录信息
        iSysUserService.repackUserInfo(sysUser, result);
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(sysUser, loginUser);

        baseCommonService.addLog("用户名: " + sysUser.getUsername() + ",登录成功！", CommonConstant.LOG_TYPE_1, null, loginUser);
        return result;
    }
}
